# coding=utf-8
"""
Author: Mr.夏末
@Function: 京东滑块验证码
pip install opencv-python
"""

import base64,pyautogui
import time

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# 使用options，去掉自动化软件控制的标识
from class10.demo06 import FindPic, slide_by_pyautogui

option = Options()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_argument('--disable-blink-features=AutomationControlled')

##关掉密码弹窗
prefs = {}
prefs['credentials_enable_service'] = False
prefs['profile.password_manager_enabled'] = False
option.add_experimental_option('prefs', prefs)

driver = webdriver.Chrome(options=option)
driver.implicitly_wait(10)
driver.maximize_window()
# 打开12306登录页
driver.get('https://passport.jd.com/new/login.aspx')
driver.find_element('xpath', "//a[text()='账户登录']").click()
driver.find_element('xpath', '//input[@id="loginname"]').send_keys('18854725236')
driver.find_element('xpath', '//input[@id="nloginpwd"]').send_keys('18854725236')
driver.find_element('xpath', '//a[@id="loginsubmit"]').click()

while True:
    # 获取背景图和滑块元素
    bimg = driver.find_element('xpath', '//div[@class="JDJRV-bigimg"]/img')
    simg = driver.find_element('xpath', '//div[@class="JDJRV-smallimg"]/img')
    # 获取src属性
    src_bimg = bimg.get_attribute('src')
    src_simg = simg.get_attribute('src')
    # src里面包含了图片的base64编码，截掉前缀
    # print(src_bimg)
    base64_bimg = src_bimg[src_bimg.index(',') + 1:]
    base64_simg = src_simg[src_simg.index(',') + 1:]
    # base64转二进制
    byte_bimg = base64.b64decode(base64_bimg)
    byte_simg = base64.b64decode(base64_simg)

    # 保存图片
    # 先打开一张图片，如果没有就会新建
    f = open('./bimg.jpg', mode='wb')
    # 写入二进制
    f.write(byte_bimg)
    # 关闭
    f.close()

    # 先打开一张图片，如果没有就会新建
    f = open('./simg.jpg', mode='wb')
    # 写入二进制
    f.write(byte_simg)
    # 关闭
    f.close()

    x = FindPic()
    print(x)

    # 处理缩放
    x = int(x * 1.25 * 278 / 360)

    time.sleep(1)
    # 获取滑块相对网页的位置
    print(simg.location)
    # print(driver.get_window_size())

    xx = simg.location.get('x')
    yy = simg.location.get('y')
    # 放大
    xx = int(xx * 1.25)
    yy = int(yy * 1.25)

    slide_by_pyautogui(xx+20,yy+90+20,x)

    try:
        time.sleep(2)
        simg = driver.find_element('xpath', '//div[@class="JDJRV-smallimg"]/img')
        elex = simg.size.get('width')
        print(simg.size)
        if elex < 1:
            break
    except Exception as e:
        print(e.__str__())
        break

driver.quit()